﻿using AchieveBLL;
using AchieveCommon;
using AchieveEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using AchieveManageWeb.Models.ActionFilters;
using AchieveManageWeb.Models;
using AchieveDAL;

namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    //项目管理模块控制器
    public class ProjectController : Controller
    {

        #region //视图控制器

        public ActionResult Index()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "项目管理")); //日志记录
            return View();
        }
        /// <summary>
        /// 创建项目单据
        /// </summary>
        /// <returns></returns>
        public ActionResult CreatePMBill()
        {
            return View();
        }
        /// <summary>
        /// 查看单一项目的横道图，传入参数ProjectID
        /// </summary>
        /// <returns></returns>
        public ActionResult gantt_singleP()
        {
            return View();
        }

        /// <summary>
        /// 项目管理--更新项目进度视图
        /// </summary>
        /// <returns></returns>
        public ActionResult PMEdit()
        {
            return View();
        }
   
        /// <summary>
        /// 项目列表
        /// </summary>
        /// <returns></returns>
        public ActionResult PMList()
        {
            return View();
        }
        /// <summary>
        /// 项目基本信息模板
        /// </summary>
        /// <returns></returns>
        public ActionResult PMModel()
        {
            return View();
        }
        /// <summary>
        /// 项目详细信息模板
        /// </summary>
        /// <returns></returns>
        public ActionResult PMModelDetail()
        {
            return View();
        }
        /// <summary>
        /// 项目商务管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMBSMgr()
        {
            return View();
        }
        public ActionResult PMBSMgrEntry()
        {
            return View();
        }
        /// <summary>
        /// 项目合同签订管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMTYMgr()
        {
            return View();
        }
        /// <summary>
        /// 项目设计管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMDNMgr()
        {
            return View();
        }
        public ActionResult PMDNMgrEntry()
        {
            return View();
        }
        /// <summary>
        /// 项目生产制造管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMMEMgr()
        {
            return View();
        }
        public ActionResult PMMEMgrEntry()
        {
            return View();
        }
        /// <summary>
        /// 项目现场施工管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMCNMgr()
        {
            return View();
        }
        public ActionResult PMCNMgrEntry()
        {
            return View();
        }
        //成本管理视图--旧
        public ActionResult PMCost()
        {
            return View();
        }
        //成本管理视图
        public ActionResult PMCostMgr()
        {
            return View();
        }      
        public ActionResult PMCostMgrEntry()
        {
            return View();
        }
        /// <summary>
        /// 搜索项目弹出框
        /// </summary>
        /// <returns></returns>
        public ActionResult PMSearch()
        {
            return View();
        }

        /// <summary>
        /// 项目管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMMaintain()
        {
            return View();
        }
        /// <summary>
        /// 项目基本信息维护界面
        /// </summary>
        /// <returns></returns>
        public ActionResult PMBasicMaintain()
        {
            return View();
        }

        public ActionResult uploadform()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }


        /// <summary>
        /// 用户角色权限页面展示--设置成本字段的查看权限
        /// </summary>
        /// <returns></returns>
        public ActionResult ProjectRoleAuthorize()
        {
            return View();
        }
        public ActionResult Edit(int id)
        {
            return View();
        }

        public ActionResult test()
        {
            return View();
        }
        public ActionResult ProjectGrid()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "生产任务单")); //日志记录
            return View();
        }
        public ActionResult ProjectGantt()
        {
            return View();
        }
        public ActionResult rpt()
        {
            return View();
        }
        public ActionResult ganttview()
        {
            return View();
        }

        //
        // GET: /Project/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        #endregion
        public string ToGanttJson(DataTable dt)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                StringBuilder sb1 = new StringBuilder();
                string plandateS = dt.Rows[i]["FPlanCommitDate"].ToString();
                string plandateE = dt.Rows[i]["FPlanFinishDate"].ToString();
                string realdateS = dt.Rows[i]["FStartDate"].ToString();
                string realdateE = dt.Rows[i]["FFinishDate"].ToString();
                sb1.AppendFormat("{{\"id\":{0},\"name\":{1},", i, "\"" + dt.Rows[i]["FBillNo"].ToString() + "\"");
                sb1.AppendFormat("\"series\":[{{\"name\":\"计划日程\",\"start\":\"{0}\",\"end\":\"{1}\",\"color\":\"{2}\" }},", plandateS, plandateE, "#f0f0f0");
                sb1.AppendFormat("{{\"name\":\"实际日程\",\"start\":\"{0}\",\"end\":\"{1}\",\"color\":\"{2}\" }}]}}", realdateS, realdateE, "#8C7853");
                if (i < dt.Rows.Count - 1)
                    sb.Append(sb1.ToString() + ",");
                else
                    sb.Append(sb1.ToString());
            }
            sb.Append("]");
            return sb.ToString();
        }
        /// <summary>
        /// 获取主生产计划的子生产计划单，即部件作业计划，分层显示，subclass=1,2,3；subclass=1同时显示无法分层的订单；
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProjectEntry()
        {
            string FBillNo = Request["FBillNo"];
            int subclass = Request["subclass"] == null ? 0 : Convert.ToInt32(Request["subclass"]);//任务单的bom分级
            //string sort = "FBillNo desc";
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 100 : Convert.ToInt32(Request["rows"]);
            string FStatus = Request["FStatus"] == null ? "" : Request["FStatus"];
            string strWhere = "1=1";
            if (FStatus == "finished")//已完成
            {
                strWhere += string.Format(" and FStatus > 2 ");
            }
            else if (FStatus == "unFinished")//未完成
            {
                strWhere += string.Format(" and FStatus < 3 ");
            }
            else if (FStatus == "overdue")//逾期
            {
                strWhere += string.Format(" and FStatus < 3 ");
                strWhere += " and FPlanFinishDate < '" + DateTime.Now.Date + "'";
            }
            else if (FStatus == "notStart")//首道工序未开工预警
            {
                strWhere += string.Format(" and FStatus < 3 ");//先按未完成进行查找；
            }
            else if (FStatus == "all")//所有状态
            {
                //strWhere += string.Format(" and FStatus < 3 ");
            }

            int totalCount = 0;   //输出参数
            DataTable dtout = manufactureBLL.GetPageManufactureSubOrder(FBillNo, strWhere, subclass, pageindex, pagesize, out totalCount);
            string strJson = AchieveCommon.JsonHelper.ToJson(dtout);
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }

        /// <summary>
        /// 修改生产任务单类型，允许传入多个订单，批量处理
        /// </summary>
        /// <returns></returns>
        public ActionResult alterWorkType()
        {
            string FBillNos = Request["FBillNo"] == null ? "" : Request["FBillNo"];
            int worktypeID = Request["worktypeID"] == null ? 0 : Convert.ToInt32(Request["worktypeID"]);
            string ip = ViewData["IP"].ToString();
            string AccountName = ViewData["AccountName"].ToString();
            string RealName = ViewData["RealName"].ToString();
            string[] fBillNos = FBillNos.Trim(',').Split(',');
            string logS = "变更成功：";
            string logF = "变更失败：";
            //object vd= ViewData;
            try
            {
                for (int i = 0; i < fBillNos.Length; i++)
                {
                    if (ProjectBLL.alterWorkType(fBillNos[i], worktypeID))
                    {
                        logS += fBillNos[i] + ";";
                    }
                    else
                    {
                        logF += fBillNos[i] + ";";
                    }
                }
                if (logS.Length < 6)
                {
                    logS = "";
                }
                if (logF.Length < 6)
                {
                    logF = "";
                }
                LoggerHelper.Notes(new LogContent(ViewData, "变更订单-" + worktypeID, logS + logF, FBillNos)); //日志记录  
                return Content("{\"msg\":\"" + logS + "<br>" + logF + "\",\"success\":true}");
            }
            catch (Exception e)
            {
                LoggerHelper.ErrorAdo("变更订单异常," + worktypeID + "," + FBillNos, e);
                return Content("{\"msg\":\"设置失败！" + e.Message + "\",\"success\":false}");
                throw;
            }
        }

        /// <summary>
        /// 视图：项目节点管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PMNodeMgr() {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "项目节点管理")); //日志记录
            return View();
        }

        /// <summary>
        /// 主作业计划通用分页查询,view=Projectgrid,Dept:部门
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPageProjectInfo()
        {
            int year =string.IsNullOrWhiteSpace(Request["year"]) ? 2019 : Convert.ToInt32(Request["year"]);//订单年份            
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "FPlanCommitDate" : Request["sort"];
            string order = Request["order"] == null ? "asc" : Request["order"];
            string view = Request["view"] == null ? "ProjectGrid" : Request["view"];
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量
            string FBillNo = Request["FBillNo"] == null ? "" : Request["FBillNo"];
            string FName = Request["FName"] == null ? "" : Request["FName"];
            string FModel = Request["FModel"] == null ? "" : Request["FModel"];
            string Dept = Request["Dept"] == null ? "all" : Request["Dept"].Trim();
            string FStatus = Request["FStatus"] == null ? "" : Request["FStatus"];
            string FWORKTYPEID = Request["FWORKTYPEID"] == null ? "" : Request["FWORKTYPEID"];//订单类型，all所有
            if (!string.IsNullOrWhiteSpace(FWORKTYPEID) && FWORKTYPEID!="all")   //
                strWhere += string.Format(" and FWORKTYPEID = '{0}'", FWORKTYPEID.Trim());
            
            string FPlanCommitDate = Request["FPlanCommitDate"] == null ? "" : Request["FPlanCommitDate"];
            if (FBillNo.Trim() != "" && !SqlInjection.GetString(FBillNo))   //防止sql注入
                strWhere += string.Format(" and FBillNo like '%{0}%'", FBillNo.Trim());

            if (FName.Trim() != "" && !SqlInjection.GetString(FName))   //防止sql注入
                strWhere += string.Format(" and FName like '%{0}%'", FName.Trim());

            if (FModel.Trim() != "" && !SqlInjection.GetString(FModel))   //防止sql注入
                strWhere += string.Format(" and FModel like '%{0}%'", FModel.Trim());

            switch (Dept)
            {
                case "all"://所有部门
                    //根据当前用户角色判断所属部门，进行相关单据查询；
                    UserEntity uInfo = ViewData["Account"] as UserEntity;
                    List<string> ls = UserDAL.GetUserDepartmentsList(uInfo.ID);
                    string depts = "'',";
                    foreach (string item in ls)
                    {
                        depts += string.Format(" '{0}',", item.Trim());
                    }
                    strWhere += string.Format(" and fheadselfj0181 in ({0}) ", depts.TrimEnd(','));
                    break;
                case "other":
                    strWhere += " and  (fheadselfj0181 not like '%事业部' or fheadselfj0181 is null)";
                    break;
                default:
                    strWhere += string.Format(" and fheadselfj0181 = '{0}'", Dept.Trim());
                    break;
            }

            switch (FStatus)
            {
                case  "finished":
                     strWhere += string.Format(" and FStatus > 2 ");
                      break;
                    case  "unFinished"://未完成
                      strWhere += string.Format(" and FStatus < 3 ");
                      break;
                    case  "overdue"://逾期
                      strWhere += string.Format(" and FStatus < 3 ");
                     strWhere += " and FPlanFinishDate < '" + DateTime.Now.Date + "'";
                      break;
                    case  "notStart"://首道工序未开工预警
                      strWhere += string.Format(" and FStatus < 3 ");//先按未完成进行查找；
                      break;
                default:
                    break;
            }
                  

            if (FPlanCommitDate.Trim() != "")
                strWhere += " and FPlanCommitDate > '" + FPlanCommitDate.Trim() + "'";

            int totalCount;   //输出参数
            DataTable dt;
            string JsonRows;
            string content = "";
            switch (view)
            {
                case "unStart"://未开工订单钻取
                    dt = manufactureBLL.GetUnStartProjectDataTablePager(pageindex,pagesize, Dept, out totalCount, sort + " " + order);
                    JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + JsonRows + "}";
                    break;
                case "ProjectGantt":
                    dt = manufactureBLL.GetProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out totalCount);
                    JsonRows = ToGanttJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"JsonRows\":" + JsonRows + "}";
                    break;
                case "pSearch"://首页查询面板，精确返回对象
                    strWhere = string.Format("1=1 and FBillNo='{0}'" , FBillNo);
                     dt = manufactureBLL.GetProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out  totalCount, sort + " " + order);
                    JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + JsonRows + "}";
                    break;
                case "rush"://紧急订单钻取 
                    strWhere = "1=1";
                    strWhere += " and  FWORKTYPEID = 68 ";
                    strWhere += " and  DATEPART(yyyy,FCommitDate)=" + year;
                    switch (Dept)
                    {
                        case "汇总":
                            break;
                        case "其他":
                            strWhere += string.Format(" and fheadselfj0181 is null ");
                            break;
                        default:
                            strWhere += string.Format(" and fheadselfj0181 = '{0}'", Dept.Trim());
                            break;
                    }
                    dt = manufactureBLL.GetProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out  totalCount, sort + " " + order);
                    JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + JsonRows + "}";
                    break;
                case "comm"://紧急订单中普通订单钻取 
                    strWhere = "1=1";
                    strWhere += " and  FWORKTYPEID != 68 ";
                    strWhere += " and  DATEPART(yyyy,FCommitDate)=" + year;
                    switch (Dept)
                    {
                        case "汇总":
                            break;
                        case "其他":
                            strWhere += string.Format(" and fheadselfj0181 is null ");
                            break;
                        default:
                            strWhere += string.Format(" and fheadselfj0181 = '{0}'", Dept.Trim());
                            break;
                    }
                    dt = manufactureBLL.GetProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out  totalCount, sort + " " + order);
                    JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + JsonRows + "}";
                    break;
                case "ProjectGrid"://20190226 任务单master grid,单据管理查询
                    if (FStatus == "unFinished")//当其他查询条件为空时，默认查询为未完工主单，临时制定查询算法，散单使用虚拟主单！20190729
                    {
                        dt = manufactureBLL.GetPageUnClosedMainProject((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out totalCount, sort + " " + order);
                        JsonRows = JsonHelper.ToJson(dt);
                    }
                    else if (FStatus == "notStart")//首道工序未开工预警，本界面返回主单，实际未开工多为子单，如何解决？
                    {
                        dt = manufactureBLL.GetNotStartProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out totalCount, sort + " " + order);
                        JsonRows = JsonHelper.ToJson(dt);
                    }
                    else if (FStatus == "includeSub")//不区分主单子单，返回所有的单据
                    {
                        dt = manufactureBLL.GetProjectDataTablePager((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out  totalCount, sort + " " + order);
                        JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    }
                    else //默认条件条件查询时，按主单显示
                    {
                        dt = manufactureBLL.GetPageMainProject((pageindex - 1) * pagesize + 1, pageindex * pagesize, strWhere, out totalCount, sort + " " + order);
                        JsonRows = AchieveCommon.JsonHelper.ToJson(dt);
                    }

                    content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + JsonRows + "}";
                    break;

                default:
                    break;

            }
            return Content(content);
        }
        /// <summary>
        /// 获取工序计划表，输入FBillNo，ICMO.FBillNo==shworkbill.FICMONO，暂不支持分页
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPageProcessInfo()
        {
            //首先获取前台传递过来的参数          
            string FBillNo = Request["FBillNo"] == null ? "" : Request["FBillNo"];

            StringBuilder sqlsb = new StringBuilder();
            sqlsb.Append("select a.ficmono,a.fitemid,b.FQTYPLAN,b.FPLANSTARTDATE,b.FPLANENDDATE,b.FStartWorkDate,");
            sqlsb.Append("b.FEndWorkDate,b.fcheckdate,b.fopernote,b.fstatus,b.FWorkCenterID,b.ffinishtime,a.ficmointerid, b.fwbinterid,b.fentryid,b.ftotalworktime,b.FEntrySelfz0374,b.FEntrySelfz0375  ");
            sqlsb.Append("from SHWORKBILL as a left join shworkbillentry as b  on a.FInterID=b.FInterID where a.ficmono='" + FBillNo + "'");

            string content = "";
            if (true)//view == "ProjectGrid")
            {
                string strJson = new ProjectBLL().GetJsonFromSqlK3(sqlsb.ToString());
                int totalCount = 100;
                // string strJson = new ProjectBLL().GetJsonPager("ICMO", "FBillNo,FStatus,FQty,FCommitQty,FPlanCommitDate,FPlanFinishDate,FStartDate,FFinishDate,FType,FWorkShop,FItemID", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            }

            return Content(content);
        }
        /// <summary>
        /// 用于Web导出
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">文件名</param> 
        //public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
        //{

        //    HttpContext curContext = HttpContext.Current;

        //    // 设置编码和附件格式
        //    curContext.Response.ContentType = "application/vnd.ms-excel";
        //    curContext.Response.ContentEncoding = Encoding.UTF8;
        //    curContext.Response.Charset = "";
        //    curContext.Response.AppendHeader("Content-Disposition",
        //        "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));

        //    curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
        //    curContext.Response.End();

        //}
        /// <summary>
        /// 导出Excel，前端采用模拟表单传入数据
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportExcel()
        {
            string jsondata = Request.Params["bodyData"];
            //创建Excel文件的对象
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            if (!string.IsNullOrWhiteSpace(jsondata))
            {
                DataTable dt = JsonHelper.JsonToDataTable(jsondata);
                NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                for (int i1 = 0; i1 < dt.Columns.Count; i1++)
                {
                    row1.CreateCell(i1).SetCellValue(dt.Columns[i1].ToString());
                }

                int i = 0;
                foreach (DataRow item in dt.Rows)
                {
                    i = i + 1;
                    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        rowtemp.CreateCell(j).SetCellValue(item[j].ToString());
                    }

                }
            }




            ////创建Excel文件的对象
            //NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            ////添加一个sheet
            //NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
            ////int pager_totalcount = (int)Session["pager_totalcount"];
            //int totalCount = 0;
            ////获取list数据
            //List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", 2, 1, out totalCount);

            ////给sheet1添加第一行的头部标题
            //NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
            ////创建时间	名称	商户订单号 | 交易号	对方	金额(元)	状态
            //row1.CreateCell(0).SetCellValue("编号");
            //row1.CreateCell(1).SetCellValue("标题");
            //row1.CreateCell(2).SetCellValue("内容");

            //int Width = 256;
            //sheet1.SetColumnWidth(0, 10 * Width);
            //sheet1.SetColumnWidth(1, 25 * Width);
            //sheet1.SetColumnWidth(2, 60 * Width);
            //if (infoList != null)
            //{
            //    var list = infoList.OrderByDescending(p => p.ID);

            //    if (list != null)
            //    {
            //        int i = 0;
            //        //将数据逐步写入sheet1各个行
            //        foreach (var item in list)
            //        {
            //            i = i + 1;
            //            NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
            //            rowtemp.CreateCell(0).SetCellValue(item.ID.ToString());
            //            rowtemp.CreateCell(1).SetCellValue(item.Title == null ? "" : item.Title.ToString());
            //            rowtemp.CreateCell(2).SetCellValue(item.Content == null ? "" : item.Content.ToString());
            //        }
            //    }
            //}


            //int RCount = dt.Rows.Count;
            //int CCount = dt.Columns.Count;
            //for (int x = 0; x < RCount; x++)
            //{
            //    for (int y = 0; y < CCount; y++)
            //    {
            //        sheet1.
            //        sheet1.Cells[x + 1, y].PutValue(dt.Rows[x][y] + "");
            //    }
            //}
            // 写入到客户端 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出项目", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

        }


        public ActionResult GetGanttDemo()
        {
            //for gantt edit, not used
            StringBuilder sb = new StringBuilder();
            sb.Append("{\"tasks\":    [");
            sb.Append("{\"id\": -1, \"name\": \"Gantt editor\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 0, \"status\": \"STATUS_ACTIVE\", \"depends\": \"\", \"canWrite\": true, \"start\": 1396994400000, \"duration\": 20, \"end\": 1399586399999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": true},");
            sb.Append("{\"id\": -2, \"name\": \"coding\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 1, \"status\": \"STATUS_ACTIVE\", \"depends\": \"\", \"canWrite\": true, \"start\": 1396994400000, \"duration\": 10, \"end\": 1398203999999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": true},");
            sb.Append("{\"id\": -3, \"name\": \"gantt part\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 2, \"status\": \"STATUS_ACTIVE\", \"depends\": \"\", \"canWrite\": true, \"start\": 1396994400000, \"duration\": 2, \"end\": 1397167199999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": false},");
            sb.Append("{\"id\": -4, \"name\": \"editor part\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 2, \"status\": \"STATUS_SUSPENDED\", \"depends\": \"3\", \"canWrite\": true, \"start\": 1397167200000, \"duration\": 4, \"end\": 1397685599999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": false},");
            sb.Append("{\"id\": -5, \"name\": \"testing\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 1, \"status\": \"STATUS_SUSPENDED\", \"depends\": \"2:5\", \"canWrite\": true, \"start\": 1398981600000, \"duration\": 5, \"end\": 1399586399999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": true},");
            sb.Append("{\"id\": -6, \"name\": \"test on safari\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 2, \"status\": \"STATUS_SUSPENDED\", \"depends\": \"\", \"canWrite\": true, \"start\": 1398981600000, \"duration\": 2, \"end\": 1399327199999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": false},");
            sb.Append("{\"id\": -7, \"name\": \"test on ie\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 2, \"status\": \"STATUS_SUSPENDED\", \"depends\": \"6\", \"canWrite\": true, \"start\": 1399327200000, \"duration\": 3, \"end\": 1399586399999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": false},");
            sb.Append("{\"id\": -8, \"name\": \"test on chrome\", \"progress\": 0, \"progressByWorklog\": false, \"relevance\": 0, \"type\": \"\", \"typeId\": \"\", \"description\": \"\", \"code\": \"\", \"level\": 2, \"status\": \"STATUS_SUSPENDED\", \"depends\": \"6\", \"canWrite\": true, \"start\": 1399327200000, \"duration\": 2, \"end\": 1399499999999, \"startIsMilestone\": false, \"endIsMilestone\": false, \"collapsed\": false, \"assigs\": [], \"hasChild\": false} ],");
            sb.Append("\"resources\": [");
            sb.Append("{\"id\": \"tmp_1\", \"name\": \"Resource 1\"},");
            sb.Append("{\"id\": \"tmp_4\", \"name\": \"Resource 4\"}],");
            sb.Append("\"roles\":       [");
            sb.Append("{\"id\": \"tmp_1\", \"name\": \"Project Manager\"},");
            sb.Append("{\"id\": \"tmp_4\", \"name\": \"Customer\"}");
            sb.Append("], \"canWrite\":    true, \"canDelete\":true, \"canWriteOnParent\": true, \"canAdd\":true}");
            return Content(sb.ToString());
        }

        //
        // GET: /Project/

    
        /// <summary>
        /// 新增项目单据--保存
        /// </summary>
        /// <returns></returns>
        /// 
        public ActionResult SelectDepartment()
        {
            string sql = " select Id,DepartmentName from tbDepartment where ParentID=0";
            string strJson = JsonHelper.GetJsonFromSql(sql);
            return Content(strJson);
        }


        public ActionResult AddNewProject()
        {
            try
            {
                string ProjectID = SqlHelper.GetSerialNumber("tbProject", "ProjectID");
                string ProjectNo = string.IsNullOrWhiteSpace(Request["ProjectNo"]) ? "PM" + ProjectID : Request["ProjectNo"];
                // string ProjectNo = Request["ProjectNo"] == null ? "PM" + ProjectID : Request["ProjectNo"];
                string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
                if (string.IsNullOrWhiteSpace(ProjectName) || SqlInjection.GetString(ProjectName))
                {
                    return Content("{\"msg\":\"错误！项目名称存在非法字符！\",\"success\":false}");
                }
                string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
                string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
                string Remark = Request["Remark"] == null ? "" : Request["Remark"];
                string FNumber = Request["FNumber"] == null ? "" : Request["FNumber"];


                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（Remark）中存在非法字符！\",\"success\":false}");
                }
                if (Request["Department"] == null)
                {
                    return Content("{\"msg\":\"请选择部门！\",\"success\":false}");

                }
                string Department = Request["Department"] == null ? "" : Request["Department"];
                UserEntity uInfo = ViewData["Account"] as UserEntity;

                List<string> sqllist = new List<string>();
                //生成增加主表记录sql
                string mainsql = string.Format("insert into tbProject (ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,Remark,CreateBy,CreateTime,department,FNumber) ");
                mainsql += string.Format(" values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}');", ProjectID, ProjectNo, ProjectName, ProjectManager, ProjectClerk, Remark, uInfo.AccountName, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"), Department, FNumber);
                sqllist.Add(mainsql);
                //生成添加节点子表SQL                
                string InfoID = AchieveCommon.SqlHelper.GetSerialNumber("tbMgrNodeInfo", "InfoID");//获取起始节点编号
                string AppendListID = AchieveCommon.SqlHelper.GetSerialNumber("tbMgrNodeInfo", "AppendListID");//获取起始附件清单编号
                long lastInfoID = long.Parse(InfoID);
                long lastAppendListID = long.Parse(AppendListID);
                //商务节点
                StringBuilder strSqlbs = new StringBuilder();
                strSqlbs.Append("insert into tbMgrNodeInfo(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlbs.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 2, "项目商务", lastAppendListID++.ToString());
                sqllist.Add(strSqlbs.ToString());
                //技术节点
                StringBuilder strSqlty = new StringBuilder();
                strSqlty.Append("insert into tbMgrNodeInfo(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlty.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 3, "合同签订", lastAppendListID++.ToString());
                sqllist.Add(strSqlty.ToString());
                //设计节点
                StringBuilder strSqldn = new StringBuilder();
                strSqldn.Append("insert into tbMgrNodeInfo(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqldn.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 4, "项目设计", lastAppendListID++.ToString());
                sqllist.Add(strSqldn.ToString());
                //生产节点
                StringBuilder strSqlme = new StringBuilder();
                strSqlme.Append("insert into tbMgrNodeInfo(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlme.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 5, "生产制造", lastAppendListID++.ToString());
                sqllist.Add(strSqlme.ToString());
                //施工节点
                StringBuilder strSqlcn = new StringBuilder();
                strSqlcn.Append("insert into tbMgrNodeInfo(InfoID,projectID,nodeid,nodename,AppendListID) ");
                strSqlcn.AppendFormat(" values ('{0}','{1}',{2},'{3}','{4}');", lastInfoID++.ToString(), ProjectID, 6, "现场施工", lastAppendListID++.ToString());
                sqllist.Add(strSqlcn.ToString());
                int id = 0;
                id = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, sqllist);
                if (id > 0)
                {
                    AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "项目管理", "添加项目"+ProjectNo,ProjectName)); //日志记录
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"添加失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

        }

        /// <summary>
        /// 根据projectid删除项目主表即节点子表，不处理附件！
        /// </summary>
        /// <returns></returns>
        public ActionResult DelProjectByID()
        {
            try
            {
                string projectID = Request["ID"] == null ? "" : Request["ID"];
                if (!string.IsNullOrEmpty(projectID))
                {
                    List<string> sqllist = new List<string>();
                    sqllist.Add(string.Format("delete tbProject where ProjectID = '{0}' ;", projectID));
                    sqllist.Add(string.Format("delete tbMgrNodeInfo where ProjectID = '{0}' ;", projectID));
                    int x = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, sqllist);
                    if (x > 0)
                    {
                        AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "项目管理", "删除项目"+projectID)); //日志记录
                        return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                    }
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！项目id为空\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
            }
        }
        /// <summary>
        /// 根据projectid对项目进行确认或取消确认！下达或取消下达
        /// </summary>
        /// <returns></returns>
        public ActionResult confirmProjectByID()
        {
            try
            {
                string projectID = Request["ID"] == null ? "" : Request["ID"];
                string confirm = Request["confirm"] == null ? "" : Request["confirm"];
                if (!string.IsNullOrEmpty(projectID))
                {
                    int status = 0;
                    switch (confirm)
                    {
                        case "confirm":
                            status = 1;
                            break;
                        case "1":
                            status = 1;
                            break;
                        case "unconfirm":
                            status = 0;
                            break;
                        case "0":
                            status = 0;
                            break;
                        case "2":
                            status = 2;
                            break;
                        case "3":
                            status = 3;
                            break;
                        case "4":
                            status = 4;
                            break;

                        default:
                            status = Convert.ToInt32(confirm);
                            break;
                    }
                    int x = AchieveBLL.ProjectBLL.confirmProjectByID(projectID, status);
                    if (x > 0)
                    {
                        AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "项目管理", "修改项目状态"+confirm)); //日志记录
                        return Content("{\"msg\":\"状态修改成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"状态修改失败！\",\"success\":false}");
                    }

                }
                else
                {
                    return Content("{\"msg\":\"操作失败！项目id为空\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"操作失败," + ex.Message + "\",\"success\":false}");
            }
        }

        /// <summary>
        /// 编辑项目单据主信息、基本信息
        /// </summary>
        /// <returns></returns>
        public ActionResult EditBasicProject()
        {
            try
            {
                string ProjectID;
                if (string.IsNullOrWhiteSpace(Request["ProjectID"]))
                {
                    throw new Exception("没有获取到ProjectID");
                }
                else
                {
                    ProjectID = Request["ProjectID"];
                }


                string ProjectNo = string.IsNullOrWhiteSpace(Request["ProjectNo"]) ? "PM" + ProjectID : Request["ProjectNo"];
                string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
                string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
                string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
                string Remark = Request["Remark"] == null ? "" : Request["Remark"];
                string Department = Request["Department"] == null ? "" : Request["Department"];
                string FNumber = Request["FNumber"] == null ? "" : Request["FNumber"];  //物料代码
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"更新失败！备注（remark）中存在非法字符！\",\"success\":false}");
                }

                UserEntity uInfo = ViewData["Account"] as UserEntity;
                StringBuilder strSql = new StringBuilder();
                strSql.Append("update tbProject set ");
                strSql.Append("ProjectNo =@ProjectNo,ProjectName=@ProjectName,ProjectManager=@ProjectManager,ProjectClerk=@ProjectClerk,Remark=@Remark,department=@department,FNumber=@FNumber,UpdateTime=@UpdateTime,UpdateBy=@UpdateBy");
                strSql.Append(" where ProjectID=@ProjectID ");

                SqlParameter[] parameters = {
			            new SqlParameter("@ProjectID", ProjectID) , 
                        new SqlParameter("@ProjectNo", ProjectNo) ,            
                        new SqlParameter("@ProjectName",ProjectName) ,            
                        new SqlParameter("@ProjectManager",ProjectManager) ,            
                        new SqlParameter("@ProjectClerk", ProjectClerk) ,            
                        new SqlParameter("@Remark", Remark) ,            
                        new SqlParameter("@department", Department) ,  
                        new SqlParameter("@FNumber", FNumber),
                        new SqlParameter("@UpdateTime", DateTime.Now) ,            
                        new SqlParameter("@UpdateBy", uInfo.AccountName) ,  
            };
                int id = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
                if (id > 0)
                {
                    return Content("{\"msg\":\"更新成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"更新失败！\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"更新失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

        }
        /// <summary>
        /// 项目管理甘特图
        /// </summary>
        /// <returns></returns>
        public ActionResult PMGantt()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "项目管理甘特图")); //日志记录
            return View();
        }
        /// <summary>
        /// 旧代码，维护阶段，由于采用gantt2，已不再使用，用PMGanttJson（）替代
        /// </summary>
        /// <returns></returns>
        public ActionResult PMGanttJsonForGantt1()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "CreateTime" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            string view = Request["view"] == null ? "" : Request["view"];

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 20 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
            string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
            string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
            string txtAddBeginDate = Request["txtAddBeginDate"] == null ? "" : Request["txtAddBeginDate"];
            string txtAddEndDate = Request["txtAddEndDate"] == null ? "" : Request["txtAddEndDate"];

            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))   //防止sql注入
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());

            if (ProjectName.Trim() != "" && !SqlInjection.GetString(ProjectName))   //防止sql注入
                strWhere += string.Format(" and ProjectName like '%{0}%'", ProjectName.Trim());

            if (ProjectManager.Trim() != "" && !SqlInjection.GetString(ProjectManager))   //防止sql注入
                strWhere += string.Format(" and ProjectManager = '{0}'", ProjectManager.Trim());

            if (txtAddBeginDate.Trim() != "")
                strWhere += " and CreateTime > '" + txtAddBeginDate.Trim() + "'";
            if (txtAddEndDate.Trim() != "")
                strWhere += " and CreateTime < '" + txtAddEndDate.Trim() + "'";

            int totalCount;   //输出参数 
            DataTable projectdt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);


            StringBuilder jsonResult = new StringBuilder();
            jsonResult.Append("[");

            for (int i = 0; i < projectdt.Rows.Count; i++)
            {
                projectInfo pi = new projectInfo();
                pi.ProjectID = projectdt.Rows[i]["ProjectID"].ToString();
                pi.ProjectNo = projectdt.Rows[i]["ProjectNo"].ToString();
                pi.ProjectName = projectdt.Rows[i]["ProjectName"].ToString();
                //查询子表，获取项目节点信息
                string sql2 = string.Format("select NodeID,NodeName,PSTime,PETime,RSTime,RETime from tbMgrNodeInfo where ProjectID='{0}'", projectdt.Rows[i]["ProjectID"]);
                DataTable dtnode = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sql2);
                foreach (DataRow rownode in dtnode.Rows)
                {
                    if (rownode["NodeID"].ToString() == "2")
                    {
                        pi.business.NodeName = rownode["NodeName"].ToString();
                        pi.business.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.business.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.business.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.business.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "3")
                    {
                        pi.technology.NodeName = rownode["NodeName"].ToString();
                        pi.technology.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.technology.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.technology.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.technology.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "4")
                    {
                        pi.design.NodeName = rownode["NodeName"].ToString();
                        pi.design.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.design.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.design.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.design.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "5")
                    {
                        pi.manufacture.NodeName = rownode["NodeName"].ToString();
                        pi.manufacture.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.manufacture.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.manufacture.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.manufacture.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);

                    }
                    else if (rownode["NodeID"].ToString() == "6")
                    {
                        pi.construction.NodeName = rownode["NodeName"].ToString();
                        pi.construction.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.construction.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.construction.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.construction.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                }
                //根据项目对象拼接字符串

                jsonResult.Append("{{\"name\":");
                jsonResult.AppendFormat("\"{0}\",", pi.ProjectName);
                //jsonResult.AppendFormat("\"{0} {1}\",", pi.ProjectNo, pi.ProjectName);
                jsonResult.AppendFormat("\"desc\": \"{0}\",", "计划时间");
                jsonResult.AppendFormat("\"values\":[");

                //商务计划时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.business.PSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.business.PETime).ToString());
                jsonResult.Append("\"label\":\"商务\",\"desc\":\"商务计划\",\"customClass\": \"ganttRed\"},");
                //合同签订计划时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.technology.PSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.technology.PETime).ToString());
                jsonResult.Append("\"label\":\"技术\",\"desc\":\"合同签订计划\",\"customClass\": \"ganttGreen\"},");
                //设计计划时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.design.PSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.design.PETime).ToString());
                jsonResult.Append("\"label\":\"设计\",\"desc\":\"设计计划\",\"customClass\": \"ganttOrange\"},");
                //生产管理计划时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.manufacture.PSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.manufacture.PETime).ToString());
                jsonResult.Append("\"label\":\"生产\",\"desc\":\"生产计划\",\"customClass\": \"ganttRed\"},");
                //施工计划时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.construction.PSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.construction.PETime).ToString());
                jsonResult.Append("\"label\":\"施工\",\"desc\":\"施工计划\",\"customClass\": \"ganttGreen\"}");
                jsonResult.Append("]},");
                //实际时间
                jsonResult.Append("{{\"name\":");
                jsonResult.AppendFormat("\"{0}\",", pi.ProjectNo);
                jsonResult.AppendFormat("\"desc\": \"{0}\",", "实际时间");
                jsonResult.AppendFormat("\"values\":[");
                //商务实际时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.business.RSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.business.RETime).ToString());
                jsonResult.Append("\"label\":\"商务\",\"desc\":\"商务实际\",\"customClass\": \"ganttRed\"},");
                //合同签订实际时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.technology.RSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.technology.RETime).ToString());
                jsonResult.Append("\"label\":\"技术\",\"desc\":\"合同签订实际\",\"customClass\": \"ganttGreen\"},");
                //设计实际时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.design.RSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.design.RETime).ToString());
                jsonResult.Append("\"label\":\"设计\",\"desc\":\"设计实际\",\"customClass\": \"ganttOrange\"},");
                //生产管理实际时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.manufacture.RSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.manufacture.RETime).ToString());
                jsonResult.Append("\"label\":\"生产\",\"desc\":\"生产实际\",\"customClass\": \"ganttRed\"},");
                //施工实际时间
                jsonResult.AppendFormat("{{\"from\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.construction.RSTime).ToString());
                jsonResult.AppendFormat("\"to\": \"{0}\",", DateHelper.DateTimeToMilliseconds(pi.construction.RETime).ToString());
                jsonResult.Append("\"label\":\"施工\",\"desc\":\"施工实际\",\"customClass\": \"ganttGreen\"}");

                if (i < projectdt.Rows.Count - 1)//判断是否最后行
                {
                    jsonResult.Append("]},");
                }
                else
                {
                    jsonResult.Append("]}]");
                }


            }
            return Content("{\"total\": " + totalCount + ",\"rows\":" + jsonResult.ToString() + "}");
        }
        /// <summary>
        /// 项目管理甘特图的json数据,前端使用gantt2组件
        /// </summary>
        /// <returns></returns>
        public ActionResult PMGanttJson()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "CreateTime" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            string view = Request["view"] == null ? "" : Request["view"];//ProjectGantt

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 20 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string status = Request["status"] == null ? "select" : Request["status"];//项目状态，0、1、2，未确认、已确认、已完成、；select所有


            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
            //string ProjectManager = Request["ProjectManager"] == null ? "" : Request["ProjectManager"];
            //string ProjectClerk = Request["ProjectClerk"] == null ? "" : Request["ProjectClerk"];
            string txtAddBeginDate = Request["CreateTimeS"] == null ? "" : Request["CreateTimeS"];
            string txtAddEndDate = Request["CreateTimeE"] == null ? "" : Request["CreateTimeE"];

            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))   //防止sql注入
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());

            if (ProjectName.Trim() != "" && !SqlInjection.GetString(ProjectName))   //防止sql注入
                strWhere += string.Format(" and ProjectName like '%{0}%'", ProjectName.Trim());

            if (status.Trim().Length == 1)//按订单状态过滤
            {
                int statusInt = Convert.ToInt32(status);
                strWhere += string.Format(" and status = {0}", statusInt);
            }
            //if (ProjectManager.Trim() != "" && !SqlInjection.GetString(ProjectManager))   //防止sql注入
            //    strWhere += string.Format(" and ProjectManager = '{0}'", ProjectManager.Trim());

            if (txtAddBeginDate.Trim() != "")
                strWhere += " and CreateTime > '" + txtAddBeginDate.Trim() + "'";
            if (txtAddEndDate.Trim() != "")
                strWhere += " and CreateTime < '" + txtAddEndDate.Trim() + "'";

            //若传入projectid，则进行单一条件查询；
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
             if (ProjectID != "" && !SqlInjection.GetString(ProjectID)) 
	        {
                strWhere = "ProjectID='" + ProjectID + "'";
	        } 

            int totalCount;   //输出参数 
            DataTable projectdt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);


            StringBuilder jsonResult = new StringBuilder();
            jsonResult.Append("[");

            for (int i = 0; i < projectdt.Rows.Count; i++)
            {
                projectInfo pi = new projectInfo();
                pi.ProjectID = projectdt.Rows[i]["ProjectID"].ToString();
                pi.ProjectNo = projectdt.Rows[i]["ProjectNo"].ToString();
                pi.ProjectName = projectdt.Rows[i]["ProjectName"].ToString();
                pi.desc = projectdt.Rows[i]["Remark"].ToString();
                pi.manager = projectdt.Rows[i]["ProjectManager"].ToString();
                //查询子表，获取项目节点信息
                string sql2 = string.Format("select NodeID,NodeName,executor,PSTime,PETime,RSTime,RETime from tbMgrNodeInfo where ProjectID='{0}'", projectdt.Rows[i]["ProjectID"]);
                DataTable dtnode = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sql2);
                foreach (DataRow rownode in dtnode.Rows)
                {
                    if (rownode["NodeID"].ToString() == "2")
                    {
                        pi.business.NodeName = rownode["NodeName"].ToString();
                        pi.business.executor = rownode["executor"].ToString();
                        pi.business.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.business.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.business.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.business.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "3")
                    {
                        pi.technology.executor = rownode["executor"].ToString();
                        pi.technology.NodeName = rownode["NodeName"].ToString();
                        pi.technology.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.technology.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.technology.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.technology.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "4")
                    {
                        pi.design.executor = rownode["executor"].ToString();
                        pi.design.NodeName = rownode["NodeName"].ToString();
                        pi.design.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.design.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.design.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.design.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                    else if (rownode["NodeID"].ToString() == "5")
                    {
                        pi.manufacture.executor = rownode["executor"].ToString();
                        pi.manufacture.NodeName = rownode["NodeName"].ToString();
                        pi.manufacture.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.manufacture.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.manufacture.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.manufacture.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);

                    }
                    else if (rownode["NodeID"].ToString() == "6")
                    {
                        pi.construction.executor = rownode["executor"].ToString();
                        pi.construction.NodeName = rownode["NodeName"].ToString();
                        pi.construction.PSTime = rownode["PSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PSTime"]);
                        pi.construction.PETime = rownode["PETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["PETime"]);
                        pi.construction.RSTime = rownode["RSTime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RSTime"]);
                        pi.construction.RETime = rownode["RETime"] is DBNull ? DateTime.Now : Convert.ToDateTime(rownode["RETime"]);
                    }
                }
                //System.Globalization.DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
                //dtFormat.ShortDatePattern = "yyyy/MM/dd";
                //Console.WriteLine(DateTime.Now.ToString("yyyy/MM/dd", dtFormat));
                //根据项目对象拼接字符串
                jsonResult.AppendFormat("{{\"code\":\"{0}\",", pi.ProjectNo);
                jsonResult.AppendFormat("\"name\":\"{0}\",", pi.ProjectName);
                jsonResult.AppendFormat("\"mgr\":\"{0}\",", pi.manager);
                jsonResult.AppendFormat("\"desc\":\"{0}\",", pi.desc);

                jsonResult.AppendFormat("\"series\":[{{\"name\":\"{0}\",", pi.business.NodeName);//项目商务
                jsonResult.AppendFormat("\"exec\":\"{0}\",", pi.business.executor);
                jsonResult.AppendFormat("\"time\":\"{0}\",", pi.business.PSTime.ToString("MM/dd") + "-" + pi.business.PETime.ToString("MM/dd"));
                jsonResult.AppendFormat("\"start0\":\"{0}\",", pi.business.PSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end0\":\"{0}\",", pi.business.PETime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"start\":\"{0}\",", pi.business.RSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end\":\"{0}\"}},", pi.business.RETime.ToString("yyyy/MM/dd"));

                jsonResult.AppendFormat("{{\"name\":\"{0}\",", pi.technology.NodeName);//合同签订
                jsonResult.AppendFormat("\"exec\":\"{0}\",", pi.technology.executor);
                jsonResult.AppendFormat("\"time\":\"{0}\",", pi.technology.PSTime.ToString("MM/dd") + "-" + pi.technology.PETime.ToString("MM/dd"));
                jsonResult.AppendFormat("\"start0\":\"{0}\",", pi.technology.PSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end0\":\"{0}\",", pi.technology.PETime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"start\":\"{0}\",", pi.technology.RSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end\":\"{0}\"}},", pi.technology.RETime.ToString("yyyy/MM/dd"));

                jsonResult.AppendFormat("{{\"name\":\"{0}\",", pi.design.NodeName);//项目设计
                jsonResult.AppendFormat("\"exec\":\"{0}\",", pi.design.executor);
                jsonResult.AppendFormat("\"time\":\"{0}\",", pi.design.PSTime.ToString("MM/dd") + "-" + pi.design.PETime.ToString("MM/dd"));
                jsonResult.AppendFormat("\"start0\":\"{0}\",", pi.design.PSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end0\":\"{0}\",", pi.design.PETime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"start\":\"{0}\",", pi.design.RSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end\":\"{0}\"}},", pi.design.RETime.ToString("yyyy/MM/dd"));

                jsonResult.AppendFormat("{{\"name\":\"{0}\",", pi.manufacture.NodeName);//生产制造
                jsonResult.AppendFormat("\"exec\":\"{0}\",", pi.manufacture.executor);
                jsonResult.AppendFormat("\"time\":\"{0}\",", pi.manufacture.PSTime.ToString("MM/dd") + "-" + pi.manufacture.PETime.ToString("MM/dd"));
                jsonResult.AppendFormat("\"start0\":\"{0}\",", pi.manufacture.PSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end0\":\"{0}\",", pi.manufacture.PETime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"start\":\"{0}\",", pi.manufacture.RSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end\":\"{0}\"}},", pi.manufacture.RETime.ToString("yyyy/MM/dd"));

                jsonResult.AppendFormat("{{\"name\":\"{0}\",", pi.construction.NodeName);//现场施工
                jsonResult.AppendFormat("\"exec\":\"{0}\",", pi.construction.executor);
                jsonResult.AppendFormat("\"time\":\"{0}\",", pi.construction.PSTime.ToString("MM/dd") + "-" + pi.construction.PETime.ToString("MM/dd"));
                jsonResult.AppendFormat("\"start0\":\"{0}\",", pi.construction.PSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end0\":\"{0}\",", pi.construction.PETime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"start\":\"{0}\",", pi.construction.RSTime.ToString("yyyy/MM/dd"));
                jsonResult.AppendFormat("\"end\":\"{0}\"}}", pi.construction.RETime.ToString("yyyy/MM/dd"));

                if (i < projectdt.Rows.Count - 1)//判断是否最后行
                {
                    jsonResult.Append("]},");
                }
                else
                {
                    jsonResult.Append("]}]");
                }


            }
            return Content("{\"total\": " + totalCount + ",\"rows\":" + jsonResult.ToString() + "}");
        }
        public class projectNode
        {
            public int NodeID;
            public string NodeName;
            public string executor;
            public DateTime PSTime;
            public DateTime PETime;
            public DateTime RSTime;
            public DateTime RETime;

        }
        public class projectInfo
        {
            public string ProjectID;
            public string ProjectNo;
            public string ProjectName;
            public string desc;
            public string manager;
            public projectNode business = new projectNode();
            public projectNode technology = new projectNode();
            public projectNode design = new projectNode();
            public projectNode manufacture = new projectNode();
            public projectNode construction = new projectNode();
        }


        /// <summary>
        /// 项目清单的查询处理--simple
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPMList()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "ProjectID" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            //string view = Request["view"] == null ? "PMMaintain" : Request["view"];

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];

            //string CreateTimeS = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            //string CreateTimeE = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            string status = (Request["status"] == null || Request["status"] == "select") ? "" : Request["status"];//0,1,2，3 未确认、已确认，已下达，已完成

            if (ProjectID.Trim() != "" && !SqlInjection.GetString(ProjectID))   //防止sql注入
                strWhere += string.Format(" and ProjectID = '{0}'", ProjectID.Trim());
            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());
            if (ProjectName.Trim() != "" && !SqlInjection.GetString(ProjectName))
                strWhere += string.Format(" and ProjectName like '%{0}%'", ProjectName.Trim());
            if (status.Trim() != "" && !SqlInjection.GetString(status))
                strWhere += string.Format(" and status = {0}", Convert.ToInt32(status.Trim()));      

            string content = "";
            string strJson = "";
            int totalCount;   //输出参数 
            DataTable dt;
            //switch (view)
            //{
            //    case "pSearch":
            //        strWhere = string.Format("ProjectNo = '{0}'", ProjectNo.Trim());
            //        dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark,status,Department,IcmoNo,FitemNo,FName,FModel", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
            //        strJson = AchieveCommon.JsonHelper.ToJson(dt);
            //        content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            //        break;

            //    case "PMMaintain":

            dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark,status,Department,IcmoNo,FitemNo,FName,FModel,FNumber", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);



            strJson = AchieveCommon.JsonHelper.ToJson(dt);
            content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            //        break;
            //    case "PMGantt":
            //        //     int totalCount;   //输出参数
            //        // pagesize = 5;//限制甘特图输出数据量
            //        //DataTable dt = new ProjectBLL().GetDataTablePager("ICMO", "FBillNo,FStatus,FPlanCommitDate,FPlanFinishDate,FStartDate,FFinishDate,FItemID", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
            //        //string strJson = ToGanttJson(dt);
            //        //content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
            //        break;
            //    default:
            //        break;
            //}

            return Content(content);
        }
        /// <summary>
        /// 项目清单的查询处理
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllPMInfo()
        {
            string strWhere = "1=1";
            string sort = Request["sort"] == null ? "ProjectID" : Request["sort"];
            string order = Request["order"] == null ? "desc" : Request["order"];
            string view = Request["view"] == null ? "PMMaintain" : Request["view"];

            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];

            string CreateTimeS = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            string CreateTimeE = Request["CreateTime"] == null ? "" : Request["CreateTime"];
            string status = (Request["status"] == null || Request["status"] == "select") ? "" : Request["status"];//0,1,2，3 未确认、已确认，已下达，已完成

            if (ProjectID.Trim() != "" && !SqlInjection.GetString(ProjectID))   //防止sql注入
                strWhere += string.Format(" and ProjectID = '{0}'", ProjectID.Trim());
            if (ProjectNo.Trim() != "" && !SqlInjection.GetString(ProjectNo))
                strWhere += string.Format(" and ProjectNo like '%{0}%'", ProjectNo.Trim());
            if (ProjectName.Trim() != "" && !SqlInjection.GetString(ProjectName))
                strWhere += string.Format(" and ProjectName like '%{0}%'", ProjectName.Trim());
            if (status.Trim() != "" && !SqlInjection.GetString(status))
                strWhere += string.Format(" and status = {0}", Convert.ToInt32(status.Trim()));
            
            UserEntity uInfo = ViewData["Account"] as UserEntity;
            
            if (strWhere.Length<15)//无查询条件时根据当前用户所在部门过滤！！
            {
                List<string> ls = UserDAL.GetUserDepartmentsList(uInfo.ID);
                 string depts = "'',";
                    foreach (string item in ls)
                    {
                        depts += string.Format(" '{0}',", item.Trim());
                    }
                    strWhere += string.Format(" and Department in ({0}) ", depts.TrimEnd(','));
            }

            if (CreateTimeS.Trim() != "")
                strWhere += " and CreateTime > '" + CreateTimeS.Trim() + "'";
            if (CreateTimeE.Trim() != "")
                strWhere += " and CreateTime < '" + CreateTimeE.Trim() + "'";

            string content = "";
            string strJson = "";
            int totalCount;   //输出参数 
            DataTable dt;
            switch (view)
            {
                case   "pSearch":
                    strWhere=string.Format("ProjectNo = '{0}'", ProjectNo.Trim());
                     dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark,status,Department,IcmoNo,FitemNo,FName,FModel", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                     strJson = AchieveCommon.JsonHelper.ToJson(dt);
                   content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
                    break;

                case "PMMaintain":
                   
                     dt = AchieveCommon.SqlPagerHelper.GetPager("tbProject", "ProjectID,ProjectNo,ProjectName,ProjectManager,ProjectClerk,CreateBy,CreateTime,UpdateTime,UpdateBy,Remark,status,Department,IcmoNo,FitemNo,FName,FModel", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                    dt.Columns.Add("EstWorkTime");

                //获取当前用户的角色及其能查看的成本项目；
               // UserEntity uInfo = ViewData["Account"] as UserEntity;
                DataTable dt_user_role = new RoleBLL().GetRoleByUserId(uInfo.ID);  //用户之前拥有的角色
                string roles = AchieveCommon.JsonHelper.ColumnToJson(dt_user_role, 0);
                //角色-字段；
                string sqlfields = "select distinct fieldName from tbRoleField where pageName='PMIndex' and roleId in (" + roles + ")";
                DataTable fields = SqlHelper.GetDataTable(SqlHelper.connStr, sqlfields);
                foreach (DataRow item in fields.Rows)
                {
                    dt.Columns.Add(item[0].ToString());//添加成本字段；
                    //判断是否输出实际成本，如需要则实时计算；
                    if (item[0].ToString() == "reaCost")
                    {         //实时查询计算实际成本；
                        foreach (DataRow dtItem in dt.Rows)
                        {
                            dtItem["reaCost"] = AchieveBLL.CostBLL.realCostCal(dtItem["ProjectNo"].ToString());
                        }
                    }
                }

                //添加附加表信息
                foreach (DataRow item in dt.Rows)
                {
                    string sql = string.Format("select max(EstWorkTime) from tbMgrNodeInfo where projectid='{0}'", item["ProjectID"].ToString());
                    item["EstWorkTime"] = SqlHelper.ExecuteScalar(SqlHelper.connStr, sql);//预估工时；
                    //string sql2 = string.Format("select estCost,budCost,stdCost,plaCost,reaCost from tbProjectCost where projectid='{0}'", item["ProjectID"].ToString());
                    string sql2 = string.Format("select estCost,budCost,stdCost,plaCost from tbProjectCost where projectid='{0}'", item["ProjectID"].ToString());
                    DataTable dtcosts = SqlHelper.GetDataTable(SqlHelper.connStr, sql2);
                    //添加相应的成本字段值
                    if (dtcosts.Rows.Count == 1)
                    {
                        foreach (DataRow item2 in fields.Rows)
                        {
                            if (item2[0].ToString() != "reaCost")
                            {
                                item[item2[0].ToString()] = dtcosts.Rows[0][item2[0].ToString()];
                            }

                        }
                    }
                }

                strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
                    break;
                case "PMGantt":
                    //     int totalCount;   //输出参数
                    // pagesize = 5;//限制甘特图输出数据量
                    //DataTable dt = new ProjectBLL().GetDataTablePager("ICMO", "FBillNo,FStatus,FPlanCommitDate,FPlanFinishDate,FStartDate,FFinishDate,FItemID", sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
                    //string strJson = ToGanttJson(dt);
                    //content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
                    break;
                default:
                    break;
            } 

            return Content(content);
        }
        /// <summary>
        /// 获取项目的节点详情
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPMNodeInfo()
        {
            //首先获取前台传递过来的参数
            string strWhere = "1=1";
            string view = Request["view"] == null ? "PMMaintain" : Request["view"];
            string ProjectID = Request["ProjectID"] == null ? "" : Request["ProjectID"];
            string NodeID = Request["NodeID"] == null ? "" : Request["NodeID"];
            if (NodeID.Trim() != "" && !SqlInjection.GetString(NodeID))   //防止sql注入
                strWhere += string.Format(" and NodeID = '{0}'", NodeID.Trim());

            //string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            //string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];

            if (ProjectID.Trim() != "" && !SqlInjection.GetString(ProjectID))   //防止sql注入
                strWhere += string.Format(" and ProjectID = '{0}'", ProjectID.Trim());
            string content = "";
            try
            {
                string sqlstr = string.Format("select * from tbMgrNodeInfo where {0}", strWhere);
                DataTable dt = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sqlstr);
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"success\": true ,\"rows\":" + strJson + "}";
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"获取数据失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

            return Content(content);
        }
        /// <summary>
        /// 获取附件列表清单，AppendListID
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAppendList()
        {
            //首先获取前台传递过来的参数
            string strWhere = "1=1";
            //string view = Request["view"] == null ? "PMMaintain" : Request["view"];
            string AppendListID = Request["AppendListID"] == null ? "" : Request["AppendListID"];
            //string ProjectNo = Request["ProjectNo"] == null ? "" : Request["ProjectNo"];
            //string ProjectName = Request["ProjectName"] == null ? "" : Request["ProjectName"];
            if (AppendListID.Trim() != "" && !SqlInjection.GetString(AppendListID))   //防止sql注入
                strWhere += string.Format(" and AppendListID = '{0}'", AppendListID.Trim());
            string content = string.Empty;
            try
            {
                string sqlstr = string.Format("select AppendID,AppendName,AppendPath,UpdateTime,UpdateBy from tbAppendInfo where AppendListID='{0}'", AppendListID);
                DataTable dt = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sqlstr);
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                content = "{\"success\": true ,\"rows\":" + strJson + "}";
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"获取数据失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

            return Content(content);
        }

        public ActionResult GetWorkTimeClass()
        {
            string content = string.Empty;
            string sqlstr = "select itemNo,itemClass,Stime from tbEstWorkEntry order by itemNo desc";
            try
            {
                DataTable dt = AchieveCommon.SqlHelper.GetDataTable(SqlHelper.connStr, sqlstr);
                string strJson = AchieveCommon.JsonHelper.ToJson(dt);
                //content = "{\"success\": true ,\"rows\":" + strJson + "}";
                content = strJson;
            }
            catch (Exception ex)
            {

                return Content("{\"msg\":\"获取数据失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
            }

            return Content(content);
        }

        /// <summary>
        /// 项目管理--更新项目节点信息，数据更新操作
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPMNode()
        {

            string NodeID = Request["NodeID"];
             UserEntity uInfo = ViewData["Account"] as UserEntity;
                string updateby = uInfo.RealName;
                string ProjectID = Request["ProjectID"];
                string PSTime = Request["PSTime"];
                string PETime = Request["PETime"];
                string RSTime = Request["RSTime"];
                string RETime = Request["RETime"];
                string Remark = Request["Remark"];
                string executor = Request["Executor"];
            if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（商务Remark）中存在非法字符！\",\"success\":false}");
                }
            try 
	{	        
		
	 

            switch (NodeID)
	{
                case   "2":
                    updateNode("2", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);//商务
                    break;
                case    "4":
                    updateNode("4", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);//设计
                    break;
                case "5":
                    string workitem1 = Request["workitem1"];//制造节点的工时项目类别
                    string workitem2 = Request["workitem2"];
                    decimal estworktime = 0;
                    if (Request["estworktime"].Length > 0)
                    {
                        estworktime = decimal.Parse(Request["estworktime"]);
                    }
                    decimal weight1 = 0, weight2 = 0;
                    if (Request["weight1"].Length > 0)
                    {
                        weight1 = decimal.Parse(Request["weight1"]);
                    }
                    if (Request["weight2"].Length > 0)
                    {
                        weight2 = decimal.Parse(Request["weight2"]);
                    }

                    updateNode("5", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark, estworktime, weight1, workitem1, weight2, workitem2); //生产
                    break;
                case "6":
                    updateNode("6", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);
                    break;
		default:
 break;
	}
               
                
                
                
         
                //更新项目主表                
                //StringBuilder strSql = new StringBuilder();
                //strSql.Append("update tbProject set UpdateTime=@UpdateTime,UpdateBy=@UpdateBy where ProjectID=@ProjectID");
                //SqlParameter[] parameters = { 
                //        new SqlParameter("@UpdateTime", DateTime.Now) ,            
                //        new SqlParameter("@UpdateBy", uInfo.AccountName) ,
                //        new SqlParameter("@ProjectID",ProjectID) 
            //};
            //    SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
            return Content("{\"msg\":\"修改成功！\",\"success\":true}");

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }
     
        /// <summary>
        /// 项目管理--更新项目节点信息，数据更新操作
        /// </summary>
        /// <returns></returns>
        public ActionResult EditPM()
        {
            try
            {
                UserEntity uInfo = ViewData["Account"] as UserEntity;
                string updateby = uInfo.RealName;
                string ProjectID = Request["ProjectID"];
                string PSTime = Request["bsPSTime"];
                string PETime = Request["bsPETime"];
                string RSTime = Request["bsRSTime"];
                string RETime = Request["bsRETime"];
                string Remark = Request["bsRemark"];
                string executor = Request["bsExecutor"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（商务Remark）中存在非法字符！\",\"success\":false}");
                }
                updateNode("2", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);//商务
                PSTime = Request["tyPSTime"];
                PETime = Request["tyPETime"];
                RSTime = Request["tyRSTime"];
                RETime = Request["tyRETime"];
                Remark = Request["tyRemark"];
                executor = Request["tyExecutor"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（合同Remark）中存在非法字符！\",\"success\":false}");
                }
                updateNode("3", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);//合同签订
                PSTime = Request["dnPSTime"];
                PETime = Request["dnPETime"];
                RSTime = Request["dnRSTime"];
                RETime = Request["dnRETime"];
                Remark = Request["dnRemark"];
                executor = Request["dnExecutor"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（设计Remark）中存在非法字符！\",\"success\":false}");
                }
                updateNode("4", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);//设计

                PSTime = Request["mePSTime"];
                PETime = Request["mePETime"];
                RSTime = Request["meRSTime"];
                RETime = Request["meRETime"];
                Remark = Request["meRemark"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（制造Remark）中存在非法字符！\",\"success\":false}");
                }
                executor = Request["meExecutor"];
                string workitem1 = Request["workitem1"];//制造节点的工时项目类别
                string workitem2 = Request["workitem2"];
                decimal estworktime = 0;
                if (Request["estworktime"].Length > 0)
                {
                    estworktime = decimal.Parse(Request["estworktime"]);
                }
                decimal weight1 = 0, weight2 = 0;
                if (Request["weight1"].Length > 0)
                {
                    weight1 = decimal.Parse(Request["weight1"]);
                }
                if (Request["weight2"].Length > 0)
                {
                    weight2 = decimal.Parse(Request["weight2"]);
                }

                updateNode("5", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark, estworktime, weight1, workitem1, weight2, workitem2); //生产

                PSTime = Request["cnPSTime"];
                PETime = Request["cnPETime"];
                RSTime = Request["cnRSTime"];
                RETime = Request["cnRETime"];
                Remark = Request["cnRemark"];
                executor = Request["cnExecutor"];
                if (SqlInjection.GetString(Remark))
                {
                    return Content("{\"msg\":\"错误！备注（施工Remark）中存在非法字符！\",\"success\":false}");
                }
                updateNode("6", executor, ProjectID, PSTime, PETime, RSTime, RETime, uInfo.AccountName, Remark);
                //更新项目主表                
                StringBuilder strSql = new StringBuilder();
                strSql.Append("update tbProject set UpdateTime=@UpdateTime,UpdateBy=@UpdateBy where ProjectID=@ProjectID");
                SqlParameter[] parameters = { 
                        new SqlParameter("@UpdateTime", DateTime.Now) ,            
                        new SqlParameter("@UpdateBy", uInfo.AccountName) ,
                        new SqlParameter("@ProjectID",ProjectID) 
            };
                SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);
                return Content("{\"msg\":\"修改成功！\",\"success\":true}");

            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"修改失败," + ex.Message + "\",\"success\":false}");
            }
        }
        //根据nodeid，projectid更新项目节点信息
        public static bool updateNode(string nodeid, string executor, string projectID, string ps, string pe, string rs, string re, string AccountName, string Remark = "", decimal estWorkTime = 0, decimal weight1 = 0, string workitem1 = "", decimal weight2 = 0, string workitem2 = "")
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update tbMgrNodeInfo set executor=@executor, Remark=@remark, EstWorkTime=@estworktime,Weight1=@weight1,workitem1=@workitem1,Weight2=@weight2,workitem2=@workitem2, ");
            strSql.Append("pstime=@pstime,petime=@petime,rstime=@rstime,retime=@retime,UpdateTime=@UpdateTime,UpdateBy=@UpdateBy where projectID=@projectID and nodeid=@nodeid");
            SqlParameter[] parameters = {	
                    new SqlParameter("@executor", executor) , 
	                   new SqlParameter("@remark", Remark) ,            
                        new SqlParameter("@estworktime",estWorkTime) , 
                         new SqlParameter("@weight1",weight1) , 
                         new SqlParameter("@workitem1",workitem1) ,
                         new SqlParameter("@weight2",weight2) , 
                         new SqlParameter("@workitem2",workitem2) ,
                        new SqlParameter("@pstime", ps) ,            
                        new SqlParameter("@petime",pe) , 
                         new SqlParameter("@rstime", rs) ,  
                        new SqlParameter("@retime", re) ,            
                        new SqlParameter("@projectID",projectID) ,            
                        new SqlParameter("@nodeid",nodeid) ,        
                        new SqlParameter("@UpdateTime", DateTime.Now) ,            
                        new SqlParameter("@UpdateBy", AccountName) 
            };
            int x = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);

            if (x > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
       
       
        /// <summary>
        /// 将文件上传到指定路径中保存，文件用id更名；
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        [ValidateInput(false)]
        public ActionResult uploadfile(HttpPostedFileBase file)
        {
            string info = string.Empty;
            try
            {
                UserEntity uInfo = ViewData["Account"] as UserEntity;
                string updateby = uInfo.RealName;
                string appendlistid = Request["appendlistid"] == null ? "" : Request["appendlistid"];
                if (appendlistid == "")
                {
                    info = "上传失败，附件清单id为空";
                    return Content("{\"msg\":\"" + info.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
                }
                //存附件文件
                string fileName = file.FileName;
                string AppendID = AchieveCommon.SqlHelper.GetSerialNumber("tbAppendInfo", "AppendID");
                string newFileName = string.Empty;
                //string newFilePath = string.Empty;
                string lname = string.Empty;
                string rname = string.Empty;
                //Random rd = new Random();
                //int ssss = rd.Next(1000, 9999);

                //newFileName = lname + "_" + ssss.ToString() + DateTime.Now.ToString("yyyyMMddHHmmssffff") + rname;
                rname = fileName.Substring(fileName.LastIndexOf('.'));//文件后缀
                newFileName = AppendID + rname;
                var filePath = Server.MapPath(string.Format("~/{0}", "uploads"));
                file.SaveAs(System.IO.Path.Combine(filePath, newFileName)); //存文件
                //更新附件表信息！！
                lname = fileName.Substring(0, fileName.LastIndexOf('.'));
                if (lname.Length > 100)
                {
                    fileName = lname.Substring(0, 90) + rname;
                }
                StringBuilder strSql = new StringBuilder();
                strSql.Append("insert into tbAppendInfo(");
                strSql.Append("AppendID,AppendListID,AppendName,AppendPath,UpdateBy,UpdateTime");
                strSql.Append(") values (");
                strSql.Append("@AppendID,@AppendListID,@AppendName,@AppendPath,@UpdateBy,@UpdateTime");//
                strSql.Append(") ");
                SqlParameter[] parameters = {
			            new SqlParameter("@AppendID", AppendID) ,   
                        new SqlParameter("@AppendListID", appendlistid) , 
                        new SqlParameter("@AppendName", fileName) ,            
                        new SqlParameter("@AppendPath",newFileName) , 
                        new SqlParameter("@UpdateTime", DateTime.Now), 
                        new SqlParameter("@UpdateBy", updateby) 
            };
                int x = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, strSql.ToString(), parameters);

                if (x > 0)
                {
                    info = "上传成功";
                    return Content("{\"msg\":\"" + info.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":true}");
                }
                else
                {
                    throw new Exception();
                }

            }
            catch (Exception)
            {
                info = "保存附件或更新附件记录失败！";
                return Content("{\"msg\":\"" + info.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
                throw;
            }

        }

        /// <summary>
        /// 根据id删除附件
        /// </summary>
        /// <returns></returns>
        public ActionResult DelAppendByID()
        {
            try
            {
                string AppendID = Request["ID"] == null ? "" : Request["ID"];
                string AppendPath = Request["AppendPath"] == null ? "" : Request["AppendPath"];

                if (!string.IsNullOrEmpty(AppendID) && !string.IsNullOrEmpty(AppendPath))
                {
                    List<string> sqllist = new List<string>();
                    sqllist.Add(string.Format("delete tbAppendInfo where AppendID = '{0}' ;", AppendID));
                    int x = SqlHelper.ExecuteNonQuery(SqlHelper.connStr, sqllist);
                    if (x > 0)
                    {
                        //删除文件
                        var filePath = Server.MapPath(string.Format("~/{0}", "uploads"));
                        System.IO.File.Delete(System.IO.Path.Combine(filePath, AppendPath));
                        return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                    }
                    else
                    {
                        return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                    }
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！附件id为空\",\"success\":false}");
                }
            }
            catch (Exception ex)
            {
                return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
            }
        }
 
        //public ActionResult adjustprojectplan()
        //{
        //    return View();
        //}

        /// <summary>
        /// 调整生产计划，推迟|提前，根据前端输入的生产计划单号，关联处理子生产计划单、以及关联工序计划单的日期；
        /// 模式：1、主生产计划单关联所有子生产计划单；2、子生产计划单关联bom子生产计划单；3、无子单的仅调整自身；
        /// </summary>
        /// <returns></returns>
        public ActionResult adjustprojectplanbll()
        {
             UserEntity uInfo = ViewData["Account"] as UserEntity;
            int days = string.IsNullOrWhiteSpace(Request["days"]) ? 0 : int.Parse(Request["days"]);
            string fbillno = string.IsNullOrWhiteSpace(Request["fbillno"]) ? "" : Request["fbillno"];
            string haschild = string.IsNullOrWhiteSpace(Request["hasChild"]) ? "false" : Request["hasChild"];
             bool hasChild=true;
            if (haschild=="false" || haschild=="0")    //前端有false、true，和0,1两种模式，转换为bool
	            {
                    hasChild = false;
	            } 
            string adjustmode = Request["adjustmode"] == null ? "" : Request["adjustmode"];  //目前不处理该字段，ahead/putoff,由前端days的正负值进行判定
            try
            {
                if (Math.Abs(days) > 0 && fbillno != "")
                {
                   
                    //根据输入的任务单号查询子生产任务单，两种模式：1、主生产计划单关联所有子生产计划单；2、子生产计划单关联bom子生产计划单；
                    //1、第一步找出关联的单号：
                    List<string> fbillnolist = new List<string>();
                    fbillnolist.Add(fbillno);
                    if (hasChild)//有子订单则找出子订单
                    {
                        DataTable dt = manufactureBLL.GetManufactureSubOrder(fbillno, "FStatus<3", 0);//0为找出所有后代单据
                        foreach (DataRow item in dt.Rows)
                        {
                            if (!string.IsNullOrWhiteSpace(item["FBillNo"].ToString()))
                            {
                                fbillnolist.Add(item["FBillNo"].ToString());
                            }
                        }
                    }

                    fbillnolist=fbillnolist.Distinct().ToList(); //去重复！

                    List<string> sqllist = new List<string>();
                    int x = 0;
                    for (int i = 0; i < fbillnolist.Count; i++)//进行订单和工单计划日期调整！！
                    {   
                      x+=  ProjectBLL.adjustProjectPlan(fbillnolist[i], days, uInfo.AccountName);
                    }
                    string fbillnos = string.Empty;
                    foreach (string item in fbillnolist)
                    {
                        fbillnos += item + ",";
                    }
                    if (x > 0)
                    {
                        LoggerHelper.Notes(new LogContent(ViewData, "调整计划-[" + days + "]-[" + fbillno + "]", fbillnos, x.ToString()));
                        return Content("{\"msg\":\"修改成功！调整生产计划与工序计划共计" + x + "条\",\"success\":true}");
                    }
                    else
                    {
                        LoggerHelper.Notes(new LogContent(ViewData, "调整计划-[" + days + "]-[" + fbillno + "]", fbillnos, x.ToString()));
                        return Content("{\"msg\":\"无计划日期修改！\",\"success\":false}");
                    }
                }
                throw new Exception();
            }
            catch { return Content("{\"msg\":\"出现异常，计划日期修改失败！\",\"success\":false}"); }

        }

        //
        // GET: /Project/Create



        //
        // POST: /Project/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

     

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Project/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Project/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
